import classNames from 'classnames';
import styles from './index.module.scss';
import { useEffect, useRef } from 'react';

interface Props
  extends React.DetailedHTMLProps<React.TextareaHTMLAttributes<HTMLTextAreaElement>, HTMLTextAreaElement> {
  className?: string;
  maxLength?: number;
  value?: string;
}

export default function Textarea({ className, value = '', autoFocus = true, maxLength = 100, ...rest }: Props) {
  const textRef = useRef<HTMLTextAreaElement>(null);
  useEffect(() => {
    //光标聚焦
    textRef.current?.setSelectionRange(-1, -1);
  }, []);

  return (
    <div className={styles.root}>
      {/* 文本输入框 */}
      <textarea
        ref={textRef}
        {...rest}
        value={value}
        maxLength={maxLength}
        autoFocus={autoFocus}
        className={classNames('textarea', className)}
      />
      {/* 当前字数/最大允许字数 */}
      <div className="count">
        {value.length}/{maxLength}
      </div>
    </div>
  );
}
